package lew.bing.novels;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 刘国兵 on 2019/8/20.
 *
 * @author 刘国兵
 */
public class PdfWriter implements NovelWriter{

    private String name;
    private String author;
    private String filePath;

    private Document document;

    private boolean isOpen;

    private static int perChapter = 100;

    private List<Chapter> chapters = new ArrayList<>();

    Font font;

    Font titleFont;

    public PdfWriter(String name, String author, String filePath) {
        this.name = name;
        this.author = author;
        this.filePath = filePath;
        document = new Document();
    }

    private void open() throws Exception{
        BaseFont font = BaseFont.createFont("STSONG.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
        this.font = new Font(font);
        this.titleFont = new Font(font, 36);
        com.itextpdf.text.pdf.PdfWriter.getInstance(document, new FileOutputStream(filePath));
        document.open();
        document.addAuthor(author);
        document.addTitle(name);
        isOpen = true;
    }


    @Override
    public void write(Novel novel) throws IOException {
        if (novel == null) {
            return;
        }
        if (!isOpen) {
            try {
                open();
            } catch (Exception e) {
                throw new IOException(e);
            }
        }
        // 根据数字分层
        int idx = novel.getIdx();
        int index = idx /perChapter;
        Chapter chapter;
        if (chapters.size() <= index) {
            chapter = new Chapter(String.format("第%d - %d章", index * perChapter +1, index * perChapter +perChapter), index);
            chapters.add(chapter);
        } else {
            chapter = chapters.get(index);
        }
        Section section = chapter.addSection(novel.getTitle());
        section.add(new Paragraph(novel.getTitle(), titleFont));
        section.add(new Paragraph(novel.getContent(),font));
        section.setNumberDepth(0);
        section.setTriggerNewPage(true);
    }

    @Override
    public void close() throws IOException {
        if (isOpen) {
            for (Chapter chapter : chapters) {
                try {
                    chapter.setNumberDepth(0);
                    document.add(chapter);
                    System.out.println("添加成功-"+chapter.getTitle());
                } catch (DocumentException e) {
                    e.printStackTrace();
                    throw new IOException(e.getCause());
                }
            }
            document.close();
        }
    }
}
